package net.xdclass.mq;

import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import net.xdclass.model.CouponRecordMessage;
import net.xdclass.model.ProductMessage;
import net.xdclass.service.ProductService;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @author : zhen.xue
 * @date : 2021-06-04 14:46
 */
@Slf4j
@Component
@RabbitListener(queues = "${mqconfig.stock_release_queue}")
public class ProductStockMQListener {

    @Autowired
    private ProductService productService;

    /**
     * 重复消费幂等性
     * 重复消费失败后，重新入队最大重试次数
     *
     * @param productMessage
     * @param message
     * @param channel
     * @throws IOException
     */
    @RabbitHandler
    public void releaseProductStock(ProductMessage productMessage, Message message, Channel channel) throws IOException {
        log.info("监听到消息: releaseCouponRecord消息内容:{}",productMessage);
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        boolean flag = productService.releaseProductStock(productMessage);
        try {
            if(flag){
                // 确认消息消费成功
                channel.basicAck(deliveryTag,false);
            }else{
                log.error("释放上商品库存失败 flag = false,{}",productMessage);
                // 不重新入队，需要人工处理排查
                channel.basicReject(deliveryTag,true);
            }
        } catch (IOException e) {
            log.error("释放上商品库存记录异常:{},message:{}",e,productMessage);
            channel.basicReject(deliveryTag,true);
        }
    }
}